/**
 * 
 */
package com.feib.stms.dao.jdbc.rowmapper;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;

import com.feib.stms.dao.SecuritiesDao;
import com.feib.stms.model.Group;
import com.feib.stms.model.Securities;
import com.feib.stms.util.SpringContextUtil;

/**
 * @author Jimmy Liu
 *
 */
public class SecuritiesRowMapper extends BaseRowMapper<Securities> implements RowMapper<Securities> {

	private static final long serialVersionUID = 2560985918019233712L;
	
	private SecuritiesDao securitiesDao;
	
	private Map<Long, Securities> parentCaches = new HashMap<Long, Securities>();

	public SecuritiesRowMapper() {
		super(Securities.class);
		securitiesDao = (SecuritiesDao)SpringContextUtil.getBean("securitiesDao");
	}
	
	public SecuritiesRowMapper(SecuritiesDao securitiesDao)
	{
		super(Securities.class);
		this.securitiesDao = securitiesDao;
		
		if (null == this.securitiesDao )
		{
			securitiesDao = (SecuritiesDao)SpringContextUtil.getBean("securitiesDao");
		}
	}
	
	@Override
	protected Securities doOtherMapRow(ResultSet rs, int rowNumber, Securities entity) {
		
		Group group = new Group();
		group.setGroupPk((Long)getColumnValue(rs, "GROUP_PK", Long.class));
		group.setGroupNo((String)getColumnValue(rs, "GROUP_NO", String.class));
		group.setGroupName((String)getColumnValue(rs, "GROUP_NAME", String.class));
		group.setGroupType((Integer)getColumnValue(rs, "GROUP_TYPE", Integer.class));
		entity.setGroup(group);
		
		Long parentSecuritiesPk = (Long)getColumnValue(rs, "PARENT_SECURITIES_PK", Long.class);		
		if (null != parentSecuritiesPk)
		{
			// 從 cache裡面抓取，節省與資料庫連結時間
			// 不同的Menu可能會有相同的 parentSecurities
			Securities parentSecurities = parentCaches.get(parentSecuritiesPk);
			if (null == parentSecurities)
			{
				parentSecurities = securitiesDao.getBySecuritiesPk(parentSecuritiesPk);
				parentCaches.put(parentSecurities.getSecuritiesPk(), parentSecurities);
			}
			
			entity.setParentSecurities(parentSecurities);
		}
		
		return entity;
	}

}
